<?php
namespace app\admin\controller;

class Renter extends Comm
{	
	public $vinfo;	//小区信息

	public function __construct(){
		parent::__construct();
		//获取小区
		$vinfo = model('Village')
		->alias('f')
		->join('village s','s.pid=f.id')
		->select();
		$data = [];
		foreach($vinfo as $v){
			$data[] = $v->toArray();
		}
		array_unshift($data, ['id'=>1,'pid'=>0,'name'=>'常州市','open'=>true]);
		$vinfo = json_encode($data);
		$this->vinfo = $vinfo;
	}
	//房源列表   展示所有房源
	public function renter_list(){
		$info = model('Renter')->select();	//查询租房表信息
		$count = model('Renter')->count();
		foreach($info as $k=>$v){
			if($v->state == '合租'){
				$yizu = model('hezu')->where('rid='.$v->rid.' && status="已租"')->select();
				$yizu = count($yizu);
				$v->yizu = $yizu;
			}
			$data[] = $v->toArray();
			$area = model('Village')->where('id="'.$data[$k]['area'].'"')->find();
			$vill = model('Village')->where('id="'.$data[$k]['vill'].'"')->find();
			$data[$k]['area'] = $area->name;
			$data[$k]['vill'] = $vill['name'];
		}
		$this->assign('count',$count);
		$this->assign('data',$data);
		$this->assign('vinfo',$this->vinfo);	//显示小区信息
		return $this->fetch('renter_list');
	}
	//条件搜索
	public function renter_select(){
		if(request()->isPost()){
			$cond = input('post.cond');
			$key = input('post.key');
			if($cond == 'vill'){
				$vill = model('village')->where('name="'.$key.'"')->find()->id;
				$info = model('renter')->where("vill=$vill")->select();
			}elseif($cond == 'all'){
				return $this->renter_list();
			}elseif($cond == 'status'){
				if($key == '已租'){
					$key = 1;
				}elseif($key == '未租'){
					$key = 0;
				}
				$info = model('Renter')->where("$cond='$key'")->select();
			}
			$data = [];
			$count = count($info);
			$this->assign('count',$count);
			foreach($info as $v){
				$data[] = $v->toArray();
			}
			$this->assign('vinfo',$this->vinfo);
			$this->assign('data',$data);
		}
		return $this->fetch('renter_list');
	}
	//添加房源 页面
	public function renter_add(){
		$character = model('OwnerCharacter')->select();
		$ini = model('OwnerIni')->select();
		foreach($character as $v){
			$data_character[] = $v;
		}
		foreach($ini as $v){
			$data_ini[] = $v;
		}
		$this->assign('characters',$data_character);
		$this->assign('inis',$data_ini);
		return $this->fetch();
	}
	//添加房源里的小区三级联动
	public function vill_show(){
		$info = model('village')->where('pid="'.input('post.pid').'"')->select();
		foreach($info as $v){
			$data[] = $v->toArray();
		}
		//dump($data);exit;
		$this->success($data);
	}

	//处理添加
	public function do_add(){
		$re = $this->validate(input('post.'),'Renter');
		if($re !== true){
			$this->error($re);
		}
		$files = request()->file('thumb');
		$path = ROOT_PATH.'public'.DS.'static'.DS.'upload'.DS.'owner';
		foreach($files as $file){
			$info = $file->move($path);
			if($info){
				$savename[] = $info->getSavename();
			}else{
				echo $file->getError();
			}
		}
		$_POST['ini'] = implode(',',$_POST['ini']);
		$_POST['character'] = implode(',',$_POST['character']);
		$_POST['thumb'] = $savename[0];
		$_POST['imgs'] = implode(',',$savename);
		$_POST['time'] = date('Y-m-d H:i:s',time());
		$res = model('Renter')->allowfield(true)->save($_POST);
		
		$rid = model('Renter')->getLastInsID();
		//还需要往vip表中rid字段添加房源编号,考虑业主可能有多套房子,根据rid的多寡可以添加多条记录
		//先去根据手机号查vip表
		$info = model('vip')->where('tel='.input('post.tel'))->find();
		if($info == null){
			//说明没有数据,需要添加手机号和房源rid
			$data['tel'] = input('post.tel');
			$data['rid'] = $rid;
			model('vip')->data($data)->save();
		}else{
			//否则需要将rid取出,是json字符串
			$info = model('vip')->where('tel='.input('post.tel'))->find();
			$v_rid = json_decode($info->rid,true);
			$rid = [$rid];
			$v_rid = array_merge($v_rid,$rid);
			$data['rid'] = json_encode($v_rid);
			model('vip')->where('tel='.input('post.tel'))->update($data);
		}
		if($res > 0){
			$this->success('成功');
		}
		$info = model('vip')->where('tel='.input('post.tel'))->find();
	}
	//房源展示
	public function renter_show(){
		$info = model('Renter')->where('rid='.input('get.rid'))->find();
			$data = $info->toArray();
			$area = model('Village')->where('id="'.$data['area'].'"')->find();
			$vill = model('Village')->where('id="'.$data['vill'].'"')->find();
			$data['area'] = $area->name;
			$data['vill'] = $vill['name'];
			
		$imgs = json_decode(($data['img']),true);
		$this->assign('data',$data);
		if($data['img'] != null){
			$count = count($imgs);

			$this->assign('count',$count);
			$this->assign('imgs',$imgs);
		}
		return $this->fetch();
	}
	//删除房源	删除房源表和发布表
	public function renter_del(){
		model('renter')->where('rid='.input('post.rid'))->delete();
		model('pub')->where('rid='.input('post.rid'))->delete();
	}
	//批量删除房源
	public function renter_dels(){
		$rid = json_decode(input('post.data'),true);
		if($rid[0] == ''){
			unset($rid[0]);
		}
		foreach($rid as $v){
			$info = model('renter')->where('rid='.$v)->delete();
			model('pub')->where('rid='.$v)->delete();
		}
		if($info > 0){
			$this->success('删除成功');
		}else{
			$this->error('删除失败');
		}
	}
	//添加图片
	public function img_add(){
		if(request()->isPost()){
			$files = request()->file('img');
			$path = ROOT_PATH.'public'.DS.'static'.DS.'upload'.DS.'owner';
			foreach($files as $k=>$file){
				$info = $file->move($path);
				if($info){
					$savename[] = $info->getSavename();
				}else{
					echo $file->getError();
				}
			}
			//先查询数据库里img字段有无内容,没有就直接更新,有另处理
			$info = model('Renter')->where('rid='.input('get.rid'))->find();
			if($info['img'] == null){
				$img = json_encode($savename);	//转化为json格式字符串存到数据库
				$data['img'] = $img;
				$res = model('Renter')->where('rid='.input('get.rid'))->update($data);	//这是直接添加图片,原有的数据会被覆盖
				if($res == 1){
					$this->success('添加成功');
				}
			}else{
				$img = json_decode($info['img'],true);
				$savename = array_merge($savename,$img);
				$img = json_encode($savename);	//转化为json格式字符串存到数据库
				$data['img'] = $img;
				$res = model('Renter')->where('rid='.input('get.rid'))->update($data);	//这是直接添加图片,原有的数据会被覆盖
				$res = model('pub')->where('rid='.input('get.rid'))->update($data);
				if($res == 1){
					$this->success('添加成功');
				}
			}
		}
		
		return $this->fetch();
	}

	//根据zTree选择小区展示房源
	public function vill_select(){
		$info = model('Renter')->where('vill='.input('post.id'))->select();
		foreach($info as $k=>$v){
			$data[] = $v->toArray();
			$area = model('Village')->where('id="'.$data[$k]['area'].'"')->find();
			$vill = model('Village')->where('id="'.$data[$k]['vill'].'"')->find();
			$data[$k]['area'] = $area->name;
			$data[$k]['vill'] = $vill->name;
		}
		$this->success($data);
	}

	//处理删除图片  批量删除
	public function do_del(){
		if(request()->ispost()){
			$data = json_decode(input('post.data'),true);	//获取ajax所传数据并转化为数组
			//查数据库img字段数据并转化为数组,再取差集即为删除图片
			$info = model('Renter')->where('rid='.input('get.rid'))->find();
			$img = json_decode($info->img,true);
			$res = array_diff($img,$data);
			//得到差集后继续转化为json然后更改数据库img
			$arr['img'] = json_encode($res);
			$info = model('Renter')->where('rid='.input('get.rid'))->update($arr);
			model('pub')->where('rid='.input('get.rid'))->update($arr);
			if($info > 0){
				//更新成功删除文件
				foreach($data as $v){
					$path = ROOT_PATH.'public'.DS.'static'.DS.'upload'.DS.'owner'.DS.$v;
					$e = unlink($path);
				}
				if($e == true){
					$this->success('删除成功,请刷新页面');
				}else{
					$this->error('删除失败,请刷新页面');
				}
			}
		}
	}
	//小区管理
	public function village(){
		
		$this->assign('vinfo',$this->vinfo);
		return $this->fetch();
	}
	//添加小区
	public function village_add(){
		return $this->fetch();			
	}
	public function do_village_add(){
		if(request()->isPost()){
			//判断区域是否存在,存在才能插入
			$finfo = model('village')->where('name="'.input('post.fname').'"')->select();
			if($finfo != []){
				$id = $finfo[0]->id;
				//判断小区是否存在,不存在为空数组,再插入新小区
				$sinfo = model('village')->where('name="'.input('post.sname').'"')->select();

				if($sinfo == []){				
					$data = ['pid'=>$id,'name'=>input("post.sname")];
					$type = model('village')->data($data)->save($data);
					//插入成功
					if($type == 1){
						$this->success('添加成功');
					}else{
						$this->error('添加失败');
					}
				}else{
					$this->error('小区已存在');
				}
			}else{
				//区域不存在,添加新的区和小区
				$data = ['pid'=>1,'name'=>input('post.fname')];
				model('village')->data($data)->save($data);	//添加新区
				$finfo = model('village')->where('name="'.input('post.fname').'"')->select(); 	//通过新区查新区id
				$id = $finfo[0]->id;
				$data = ['pid'=>$id,'name'=>input("post.sname")];	//添加新小区
				$type = model('village')->data($data)->save($data);
				//插入成功
					if($type == 1){
						$this->error('添加成功');
					}else{
						$this->error('添加失败');
					}
			}
			
		}
	}
	//查看业主 包含跟进信息
	public function owner_show(){
		//根据rid查vip信息
		$renter = model('renter')->where('rid='.input('get.rid'))->find();
		$oid = $renter->oid;
		$addr = $renter->addr;
		//业主名下房子个数----看有多少通过委托相同的号码
		$tel = model('owner')->where('oid='.$oid)->find()->tel;
		$count = model('owner')->where('tel='.$tel. '&& status=1')->select();
		$count = count($count);	//个数
		$this->assign('count',$count);
		$info = model('vip')->where('tel='.$tel)->find()->toArray();
		$info['addr'] = $addr;
		//查跟进数据
		$fdata = model('followinfo')->where('rid='.input('get.rid'))->order('fid desc')->select();
		$data = [];
		if($fdata != []){
			foreach($fdata as $k=>$v){
				$data[] = $v->toArray();
				$data[$k]['sid'] = $k+1;
			}
		}
		$this->assign('data',$data);
		$this->assign('info',$info);
		//dump($info);exit;
		return $this->fetch();
	}
	//添加跟进 接受数据插入 fllow表中  且负责向前台提供业主号码
	public function followinfo(){
		$data['mname'] = session('uname');
		$data['content'] = input('post.content');
		$data['date'] = date('Y-m-d H:i:s',time());
		$data['rid'] = input('get.rid');
		model('followinfo')->allowfield(true)->save($data);
		if(input('post.check') == 1){
			//提供号码
			$oid = model('renter')->where('rid='.input('get.rid'))->find()->oid;
			$tel = model('owner')->where('oid='.$oid)->find()->tel;
			$this->success($tel);
		}else{
			$this->error('no');
		}
		//model('followinfo')->allowfield(true)->save($data);
	}
	//删除跟进
	public function followinfo_del(){
		$info = model('followinfo')->where('fid='.input('post.fid'))->delete();
		if($info > 0){
			$this->success(1);
		}else{
			$this->error(0);
		}
	}

	//个人房源
	public function member_show(){
		if(request()->isPost()){
			$cond = input('post.cond');
			$key = input('post.key');
			if($cond == 'vill'){	//小区
				$vill = model('village')->where('name="'.$key.'"')->find()->id;
				$info = model('renter')->where("vill=$vill && checker='".session('uname')."'")->select();
			}elseif($cond == 'all'){	//全部
				$info = model('Renter')->where('checker="'.session('uname').'"')->select();
			}elseif($cond == 'status'){	//已租/未租
				if($key == '已租'){
					$key = 1;

				}elseif($key == '未租'){
					$key = 0;
				}
				$info = model('Renter')->where("$cond='$key' && checker='".session('uname')."'")->select();
			}elseif($cond == 'state'){	//整租/合租
				$info = model('Renter')->where("$cond='$key' && checker='".session('uname')."'")->select();
			}elseif($cond == 'ispub'){	//上架下架
				if($key == '上架'){
					$key = 1;
				}elseif($key == '下架'){
					$key = 0;
				}
				$is = model('pub')->where("$cond='$key' && mname='".session('uname')."'")->select();
				$id = [];
				foreach($is as $v){
					$id[] = $v->rid;
				}
				$info = model('Renter')->where('rid','in',$id)->select();
			}elseif($cond == 'pub'){	//可发布/不可发布
				$rid = [];
				$pub = model('pub')->select();
				foreach($pub as $v){
					$rid[] = $v->rid;
				}
				if($key == '可发布'){
					$where = [
						'rid'=>['in',$rid],
						'checker'=>session('uname')
					];
					$info = model('renter')->where($where)->select();
				}elseif($key == '不可发布'){
					$where = [
						'rid'=>['not in',$rid],
						'checker'=>session('uname')
					];
					$info = model('renter')->where($where)->select();
				}
			}
		}else{
			$info = model('Renter')->where('checker="'.session('uname').'"')->select();	//查询租房表信息
		}

		$count = count($info);
		//查询发布状态 是否可以发布  已经发布
		$pubinfo = model('pub')->order('rid')->select();
		$data = [];
		$pub = [];
		foreach($pubinfo as $v){
			$pub[] = $v->toArray();
		}
		foreach($info as $k=>$v){
			$data[] = $v->toArray();
			$area = model('Village')->where('id="'.$data[$k]['area'].'"')->find();
			$vill = model('Village')->where('id="'.$data[$k]['vill'].'"')->find();
			$data[$k]['area'] = $area->name;
			$data[$k]['vill'] = $vill['name'];
			//发布与否在于pub表
			if($pub != []){
				foreach($pub as $kk=>$vv){
					if($v['rid'] == $vv['rid']){
						$data[$k]['pub'] = '可以发布';	//可以发布
						$data[$k]['ispub'] = $vv['ispub'];
						continue 2;
					}else{
						$data[$k]['pub'] = '不可发布';	//不可以发布
						$data[$k]['ispub'] = $vv['ispub'];
					}
				}
			}else{
				$data[$k]['pub'] = '不可发布';	//不可以发布
				$data[$k]['ispub'] = 0;
			}
		}
		//显示整租合租  合租房根据小房间增加data数据
		$he = [];
		foreach($data as $k=>$v){
			if($v['state'] == '合租'){
				$hezu = model('hezu')->where('rid='.$v['rid'])->select();
				foreach($hezu as $vv){
					$he = $vv->toArray();
					$merge = array_merge_recursive($vv->toArray(),$v);
					$merge['rid'] = $merge['rid'][0];
					$merge['face'] = $merge['face'][0];
					$merge['price'] = $merge['price'][0];
					$merge['status'] = $merge['status'][0];
					$data[] = $merge;
				}
				unset($data[$k]);
			}
		}
		$this->assign('count',$count);
		$this->assign('data',$data);
		$this->assign('vinfo',$this->vinfo);	//显示小区信息
		return $this->fetch();
	}
	//准备发布房源
	public function pub(){
		$character = model('OwnerCharacter')->select();
		$ini = model('OwnerIni')->select();
		foreach($character as $v){
			$data_character[] = $v;
		}
		foreach($ini as $v){
			$data_ini[] = $v;
		}
		$info = model('pub')->where('rid='.input('get.rid'))->find();

		$renter = model('Renter')->where('rid='.input('get.rid'))->find();
		$oid = $renter->oid;
		$owner = model('Owner')->where('oid='.$oid)->find();
		$oini = explode(',',$owner->ini);
		$char =  explode(',',$owner->character);
		$this->assign('oini',$oini);
		$this->assign('char',$char);

		$this->assign('renter',$renter);
		//dump($info);exit;
		$this->assign('info',$info);
		$this->assign('characters',$data_character);
		$this->assign('inis',$data_ini);
		return $this->fetch();
	}
	//处理发布
	public function do_pub(){
		//需要将发布信息插入pub表中,将renter表中的img字段值更新到pub中,并且确认好renter与pub的关系
		//获取renter中的图片
		$renter = model('Renter')->where('rid='.input('get.rid'))->find();
		$img = $renter->img;
		$thumb = $renter->thumb;
		$_POST['ini'] = implode(',',$_POST['ini']);
		$_POST['character'] = implode(',',$_POST['character']);
		$_POST['img'] = $img;
		$_POST['thumb'] = $thumb;
		$_POST['mname'] = session('uname');
		$_POST['rid'] = input('get.rid');
		//不存在,我才插入
		$exists = model('pub')->where('rid='.input('get.rid'))->find();
		if($exists == null){
			$res = model('pub')->allowfield(true)->save($_POST);
			//更改renter表字段表示发布状态 0不可发布  1可发布 2已发布 
			if($res>0){
				$this->success('准备成功');
			}else{
				$this->error('准备失败');
			}
		}else{
			//否则代表更新
			unset($_POST['prov']);
			model('renter')->where('rid='.input('get.rid'))->update(['state'=>input('post.state'),'hu'=>input('post.hu')]);
			$res = model('pub')->where('rid='.input('get.rid'))->update($_POST);
			//更改renter表字段表示发布状态 0不可发布  1可发布 2已发布
			if($res>0){
				$this->success('更新成功');
			}else{
				$this->error('更新失败');
			}
		}
	}
	//合租
	public function hezu(){
		$info = model('hezu')->where('rid='.input('get.rid'))->select();
		$hu = model('pub')->where('rid='.input('get.rid'))->find()->hu;	//房型
		$this->assign('count',count($info));	//要求$count小于$hu  发布的户型小于等于真正的户型
		$this->assign('hu',$hu);
		$data = [];
		foreach($info as $v){
			$data[] = $v->toArray();
		}
		$this->assign('data',$data);
		return $this->fetch();
	}
	//添加合租房
	public function hezu_add(){
		$info = model('hezu')->where('rid='.input('get.rid'))->select();
		$num = [];
		foreach($info as $v){
			$num[] = $v->num;
		}
		if(in_array(input('post.num'),$num)){
			$this->error('房间号已存在');
		}else{
			$data = input('post.');
			$data['rid'] = input('get.rid');
			$data['states'] = '未租';
			$info = model('hezu')->allowfield(true)->data($data)->save();
			if($info>0){
				$this->success('添加成功');
			}else{
				$this->error('添加失败');
			}
		}
	}
	//查看合租房
	public function hezu2(){
		$this->assign('id',input('get.hid'));
		$info = model('hezu')->where('rid='.input('get.rid'))->select();
		$data = [];
		foreach($info as $v){
			$data[] = $v->toArray();
		}
		$this->assign('data',$data);
		return $this->fetch();
	}
	//删除合租房
	public function hezu_del(){
		model('hezu')->where('hid='.input('post.hid'))->delete();
	}
	//出租 合租房status
	public function chuzu(){
		//判断是否已经出租
		$status = model('hezu')->where('hid='.input('post.hid'))->find()->status;
		if($status == '已租'){
			$data['status'] = '未租';
			$data['tel'] = null; 
		}else{
			//判断是否漏传tel
			if(input('post.tel') == ''){
				$this->error('出租号码忘记填写?');
			}else{
				if(!preg_match("/^1[34578]\d{9}$/", input('post.tel'))){
					$this->error('手机号格式不正确?');
				}
				$data['tel'] = input('post.tel');
			}
			$data['status'] = '已租'; 
		}
		$info = model('hezu')->where('hid='.input('post.hid'))->update($data);
		if($info > 0){
			$this->success('处理成功');
		}else{
			$this->error('出租失败');
		}
	}
	//整租 出租
	public function zhengzu(){
		if(request()->isPost()){
			$data['rid'] = input('get.rid');
			$data['qytime'] = date('Y-m-d H:i:s',time());
			$data['endtime'] = date('Y-m-d H:i:s',strtotime('+1 year'));
			$data['paytime'] = date('Y-m-d H:i:s',strtotime('+1 month'));
			$data['vid'] = model('vip')->where('tel='.input('post.tel'))->find()->vid;
			$data['uid'] = model('member')->where('uname="'.input('post.uname').'"')->find()->uid;
			$data['price'] = input('post.price');
			//插入表contract
			$info = model('contract')->allowfield(true)->data($data)->save();
			if($info>0){
				//修改pub renter
				model('renter')->where('rid='.input('get.rid'))->update(['status'=>1]);
				model('pub')->where('rid='.input('get.rid'))->update(['status'=>1]);
				$this->success('出租成功');
			}
		}else{
			return $this->fetch();
		}
	}
	//正常出租
	public function nozu(){
		//将pub renter已租状态改为0  status
		//dump(input('post.'));exit;
		if(input('post.status') == '已租'){
			$data['status'] = 0;
		}else{
			$data['status'] = 1;
		}
		model('pub')->where('rid='.input('post.rid'))->update($data);
		$info = model('renter')->where('rid='.input('post.rid'))->update($data);
		if($info >0){
			$this->success('修改成功');
		}
	}
	//下架
	public function pub_stop(){
		if(!session('?rid') || input('post.rid') != session('rid')){
			session('rid',input('post.rid'));
		}
		
		//dump(session('rid'));
		$data['ispub'] = 0;
		$info = model('pub')->where('rid='.session('rid'))->update($data);
		if($info >= 1){
			$this->success('已下架');
		}else{
			$this->success('下架失败'.input('post.rid').session('rid'));
		}
	}
	//确认发布
	public function pub_start(){
		if(!session('?rid') || input('post.rid') != session('rid')){
			session('rid',input('post.rid'));
		}
		
		//dump(session('rid'));
		$data['ispub'] = 1;
		$info = model('pub')->where('rid='.session('rid'))->update($data);
		if($info >= 1){
			$this->success('已上架');
		}else{
			$this->success('上架失败'.input('post.rid').session('rid'));
		}
	}
}
